package com.ieasy.module.system.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.ieasy.basic.dao.IBaseDao;
import com.ieasy.basic.exception.ServiceException;
import com.ieasy.basic.model.DataGrid;
import com.ieasy.basic.model.Msg;
import com.ieasy.basic.model.Pager;
import com.ieasy.basic.model.SystemContext;
import com.ieasy.basic.util.BeanUtils;
import com.ieasy.basic.util.StringUtil;
import com.ieasy.module.common.dto.PersonInfoExcelDto;
import com.ieasy.module.common.web.servlet.WebContextUtil;
import com.ieasy.module.system.entity.PersonInfoEntity;
import com.ieasy.module.system.util.mail.SendMail;
import com.ieasy.module.system.web.form.PersonForm;
import com.ieasy.module.system.web.form.PersonInfoForm;

@Service @Transactional
public class PersonInfoService implements IPersonInfoService {
	
	@Inject
	private IBaseDao<PersonInfoEntity> basedaoPi ;
	
	@Inject
	private IPersonService personService ;
	
	@Inject
	private SendMail sendMail ;

	@Override
	public Msg add(PersonInfoForm form) {
		PersonInfoEntity entity = new PersonInfoEntity() ;
		BeanUtils.copyNotNullProperties(form, entity) ;
		
		this.basedaoPi.add(entity) ;
		
		return new Msg(true, "添加成功！");
	}

	@Override
	public Msg addOriginPerson(PersonInfoForm form) {
		try {
			if(null != form.getIds() && !"".equals(form.getIds())) {
				StringBuffer emails = new StringBuffer() ;
				
				String[] ids = form.getIds().split(",") ;
				for (String id : ids) {
						
						PersonForm p = new PersonForm() ; p.setId(id) ;
						PersonForm personForm = this.personService.get(p) ;
						
						BigInteger countSQL = this.basedaoPi.countSQL("select count(t.id) from ieasy_sys_person_info t where t.num='"+personForm.getNum()+"'", false) ;
						if(countSQL.intValue() == 0) {
							emails.append(personForm.getEmail()).append(",") ;
							
							PersonInfoEntity entity = new PersonInfoEntity() ;
							entity.setNum(personForm.getNum()) ;
							
							this.basedaoPi.add(entity) ;
							
							
						}
						
				}
				if(null != emails && emails.toString().length() > 0) {
					this.sendMail.sendUserHoubuInfo(emails.toString()) ;
				}
				return new Msg(true, "人员已加入候补列表中，请前往查看！") ;
			}
		} catch (Exception e) {
			return new Msg(false, "加入失败！") ;
		}
		return null;
	}

	@Override
	public Msg delete(PersonInfoForm form) {
		try {
			if(null != form.getIds() && !"".equals(form.getIds())) {
				String[] ids = form.getIds().split(",") ;
				for (String id : ids) {
					if(!id.equals(WebContextUtil.getCurrentUser().getUser().getEmp_id())) {
						PersonInfoEntity entity = this.basedaoPi.load(PersonInfoEntity.class, id) ;
						
						
						this.basedaoPi.delete(entity) ;
					}
				}
				return new Msg(true, "删除成功！") ;
			}
		} catch (Exception e) {
			return new Msg(false, "删除失败！") ;
		}
		return null;
	}

	@Override
	public Msg update(PersonInfoForm form) {
		PersonInfoEntity entity = this.basedaoPi.load(PersonInfoEntity.class, form.getId()) ;
		
		BeanUtils.copyNotNullProperties(form, entity) ;
		
		return new Msg(true, "修改成功！") ;
	}

	@Override
	public PersonInfoForm get(PersonInfoForm form) {
		try {
			Map<String, Object> alias = new HashMap<String, Object>();
			
			String sql = "select " +
						 "e.id, p.name, p.num, p.sex, p.birth, p.ryjb, o.id org_id, o.name org_name, pos.id position_id, pos.name position_name, p.gzjyns, p.zrbsejyns, "+
						 "e.status, e.jiaming, e.qzyw, e.qzyxq, e.hzyw, e.hzyxq, e.toCity, e.sxjn, e.lcly, e.ccsjrq, e.cqcckn, e.javaYear, e.netYear, "+
						 "e.kh, e.aj "+
						 "from ieasy_sys_person_info e " +
					 	 "left join ieasy_sys_person p on(e.num=p.num) " +
					 	 "left join ieasy_sys_org o on(o.id=p.org_id) " +
					 	 "left join ieasy_sys_position pos on(pos.id=p.position_id) " +
					 	 "where 1=1 ";
			
			
			sql = addWhere(sql, form, alias) ;
			
			PersonInfoForm f = (PersonInfoForm)this.basedaoPi.queryObjectSQL(sql, alias, PersonInfoForm.class, false) ;
			if(null == f) {
				PersonInfoForm ff = new PersonInfoForm();
				ff.setId("none") ;
				return ff ;
			}
			return f ;
		} catch (Exception e) {
			e.printStackTrace() ;
			throw new ServiceException("加载信息异常：", e) ;
		}
	}

	@Override
	public DataGrid datagrid(PersonInfoForm form) {
		if(null != form.getSort()) {
			String[] personSorts = new String[]{"num", "name", "sex"};
			if(StringUtil.arrayToString(personSorts).contains(form.getSort())) {
				SystemContext.setSort("e."+form.getSort()) ; SystemContext.setOrder(form.getOrder()) ;
			}
		}
		try {
			List<PersonInfoForm> forms = new ArrayList<PersonInfoForm>() ;
			Pager<PersonInfoForm> pager = this.find(form) ;
			if (null != pager && !pager.getDataRows().isEmpty()) {
				for(PersonInfoForm pf : pager.getDataRows()) {
					forms.add(pf) ;
				}
			}
			DataGrid dg = new DataGrid() ;
			dg.setTotal(pager.getTotal());
			dg.setRows(forms);
			return dg;
		} catch (Exception e) {
			e.printStackTrace() ;
			throw new ServiceException("加载人员列表信息异常：", e) ;
		}
	}
	
	private Pager<PersonInfoForm> find(PersonInfoForm form) {
		Map<String, Object> alias = new HashMap<String, Object>();
		String sql = "select " +
				"e.id, p.name, p.num, p.sex, p.birth, p.ryjb, o.name org_name, pos.name position_name, p.gzjyns, p.zrbsejyns, "+
				"e.status, e.jiaming, e.qzyw, e.qzyxq, e.hzyw, e.hzyxq, e.toCity, e.sxjn, e.lcly, e.ccsjrq, e.cqcckn, e.javaYear, e.netYear, "+
				"e.kh, e.aj "+
				 	 "from ieasy_sys_person_info e " +
				 	 "left join ieasy_sys_person p on(e.num=p.num) " +
				 	 "left join ieasy_sys_org o on(o.id=p.org_id) " +
				 	 "left join ieasy_sys_position pos on(pos.id=p.position_id) " +
				 	 "where 1=1 ";
		sql = addWhere(sql, form, alias) ;
		
		return this.basedaoPi.findSQL(sql, alias, PersonInfoForm.class, false) ;
	}
	
	private String addWhere(String sql, PersonInfoForm form, Map<String, Object> params) {
		if (null != form) {
			if (form.getId() != null && !"".equals(form.getId().trim())) {
				sql += " and e.id=:id";
				params.put("id", form.getId().trim());
			}
			if (form.getNum() != null && !"".equals(form.getNum().trim())) {
				sql += " and e.num like :num";
				params.put("num", "%%" + form.getNum().trim() + "%%");
			}
			if (form.getName() != null && !"".equals(form.getName().trim())) {
				sql += " and e.name like :name";
				params.put("name", "%%" + form.getName().trim() + "%%");
			}
			if (form.getSex() != null && !"".equals(form.getSex())) {
				sql += " and e.sex= :sex ";
				params.put("sex", form.getSex().trim());
			}
			if (form.getEmail() != null && !"".equals(form.getEmail().trim())) {
				sql += " and e.email like :email ";
				params.put("email", "%%" + form.getEmail().trim() + "%%");
			}
		}
		return sql;
	}
	
	public List<PersonInfoExcelDto> exportPersonInfoData(PersonInfoForm form) {
		Map<String, Object> alias = new HashMap<String, Object>();
		String sql = "select " +
				"p.name, p.num, p.sex, p.ryjb, o.name org_name, pos.name position_name, p.gzjyns, p.zrbsejyns, "+
				"e.status, e.jiaming, e.qzyw, date_format(e.qzyxq,'%Y-%m-%d') qzyxq, e.hzyw, date_format(e.hzyxq,'%Y-%m-%d') hzyxq, date_format(e.ccydr,'%Y-%m-%d') ccydr, e.toCity, e.sxjn, e.lcly, date_format(e.ccsjrq,'%Y-%m-%d') ccsjrq, e.cqcckn, e.javaYear, e.netYear, "+
				"e.kh, e.aj "+
				 	 "from ieasy_sys_person_info e " +
				 	 "left join ieasy_sys_person p on(e.num=p.num) " +
				 	 "left join ieasy_sys_org o on(o.id=p.org_id) " +
				 	 "left join ieasy_sys_position pos on(pos.id=p.position_id) " +
				 	 "where 1=1 ";
		sql = addWhere(sql, form, alias) ;
		
		return this.basedaoPi.listSQL(sql, alias, PersonInfoExcelDto.class, false) ;
	}

}
